package com.ace.user.api.interceptor;

import com.ace.user.util.LogUtil;
import com.alibaba.fastjson.JSONObject;
import com.ace.user.common.constant.C;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器,例子
 * @Author yudong
 * @Date 2018年07月03日 上午10:36
 */
@Component
@Slf4j
public class ResponseInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LogUtil.traceLogId();
        log.info("---> method:{} url->{} user-agent:{}", request.getMethod(),request.getRequestURI(),request.getHeader("User-Agent"));
        JSONObject jsonObject = new JSONObject();
        jsonObject.putAll(request.getParameterMap());
        log.info("params:{} lang:{}",jsonObject.toJSONString(),request.getSession().getAttribute("lang_session"));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long endTime = System.currentTimeMillis();
        long useTime = endTime - Long.parseLong(MDC.get(C.METHOD_START_TIME));
        log.info("<--- method:{} url{} useTime:{}ms",request.getMethod(),request.getRequestURI(),useTime);
    }
}
